<?php

class Com_tag{
	
	public $defaultAct='index';
	function __construct($ainfo=null){
		$this->model = Afun_db()->model(Acan_table_tag);
	}
	//获取指定应用的所有tag（数组中的KEY）
	function tag_data($dbname,$app="",$obj=""){
		$cachename = 'tag/'.$app;
		if(is_object($obj)){
			$cachename .= "_".$obj->cg."_".$obj->cg_user."_".$obj->uid;
		}
		$tags = Afun_cache_get($cachename);
		if(empty($tags)){
			$model = Afun_db()->model($dbname);
			$con->select = "a.tag";
			$con->where = "a.`if_auth`=1 and a.`if_del`=0 ";
			if(is_object($obj)){
				foreach($obj as $k=>$v){
					$con->where .= "and a.`$k` = '$v' ";
				}
			}
			$datas = $model->ofindAll($con);
			foreach ($datas as $key => $val) {
				if($val->tag){
					$tagrr = explode(',',$val->tag);
					if(is_array($tagrr))
					foreach ($tagrr as $key => $val) {
						if(!empty($val)){$tags[$val] = 0;}
					}
				}
			}
			if($app){
				$this->tag_to_db($app,$tags);//更新tag
			}
			Afun_cache_set($cachename,$tags);//写入缓存
		}
		return $tags;
	}
	//将获取的tag存入tag数据库
	function tag_to_db($app,$tags=""){
		if(!is_array($tags)){return false;}
		$app = Afun_new('app')->app_id($app);
		$old_tagrr = $this->tag_have($app);
		foreach ($tags as $key => $val) {
			if(!in_array($key,$old_tagrr)){
				$con->app = $app;
				$con->tag = $key;
				$this->model->save($con);
				unset($con);
				$dbup = 1;
			}
		}
		if($dbup==1){Afun_cache_rmAll('tag/');}//有数据库操作删除缓存
		return true;
	}
	//获取当前应用已有的tag数据
	function tag_have($app){
		$cachename = 'tag/old_'.$app;
		$datas = Afun_cache_get($cachename);
		if(empty($datas)){
			$app = Afun_new('app')->app_id($app);
			$con->where = "app=$app";
			$con->order = "click DESC";
			$models = $this->model->ofindAll($con);
			if(is_array($models))
			foreach ($models as $key => $val) {
				$datas[] = $val->tag;
			}
			Afun_cache_set($cachename,$datas);//写入缓存
		}
		return $datas;
	}
	//tag 点击统计
	function tag_click($app,$tag){
		$con->app = Afun_new('app')->app_id($app);
		$con->tag = $tag;
		$datas = $this->model->update("click= click+1",$con);
	}


}

?>